package com.miao.dao;

import com.miao.io.Resources;
import com.miao.pojo.User;
import com.miao.sqlSession.SqlSession;
import com.miao.sqlSession.SqlSessionFactory;
import com.miao.sqlSession.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

/**
 * @author 喵瑞恒
 * @date 2023/09/14 19:28
 **/
public class UserDaoImpl implements IUserDao {
    public List<User> findAll() throws Exception {
        //1.根据配置文件路径加载成字节输入流存到内存中，注意：此时配置文件还未解析
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlConfig.xml");

        //2.解析了配置文件，封装了Configuration对象，创建了SqlSessionFaction工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        //3.生产sqlSession对象，创建了执行器对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.调用sqlSession方法
        List<User> list = sqlSession.selectList("user.selectList", null);
        System.out.println(list);
        //5.释放资源
        sqlSession.close();
        return list;
    }

    public User findByCondition(User user) throws Exception {
        //1.根据配置文件路径加载成字节输入流存到内存中，注意：此时配置文件还未解析
        InputStream resourceAsStream = Resources.getResourceAsStream("SqlConfig.xml");

        //2.解析了配置文件，封装了Configuration对象，创建了SqlSessionFaction工厂对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);

        //3.生产sqlSession对象，创建了执行器对象
        SqlSession sqlSession = sqlSessionFactory.openSession();

        //4.调用sqlSession方法
        User user3 = new User();
        user.setId(1);
        user.setUsername("miao");
        User user2 = sqlSession.selectOne("user.selectOne",user3);

        System.out.println(user2);

        //5.释放资源
        sqlSession.close();
        return user2;
    }
}
